package gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.ListSelectionModel;
import javax.swing.SpringLayout;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.Border;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;

import mappers.ContingentMapper;
import mappers.MemberMapper;
import domains.Contingent;
import domains.Member;

public class AddContingentGUI {
	private JFrame addContingentFrame;
	private JTable membersTable;
	private JScrollPane tableScrollPane;
	private JPanel tablePanel, panelRight, panelRightSide, contingentPanel, btnPanel;
	private JSeparator js;
	private JLabel startDateLbl, fNameLbl, lNameLbl, memberIdLbl, endDateLbl;
	private JButton addBtn, cancelBtn;
	private JTextField startDateTF, endDateTF;
	private DateTime date;
	private String startDateString;
	private Object memberId;
	
	public AddContingentGUI() {

		MemberMapper mMapper = new MemberMapper();
		final List<Member> data = mMapper.selectUnpaidMembers();
		final MyTableModel m = new MyTableModel(data);
	    date = new DateTime();
	    
		membersTable = new JTable(m);
		membersTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
	
		startDateString = date.getDayOfMonth() + "-" 
				+ date.getMonthOfYear() + "-" + date.getYear();
		
		addBtn = new JButton("Tilføj");
		addBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				DateTime start = parseDateTime(startDateTF.getText());
				String endDate = endDateTF.getText();
				DateTime end = parseDateTime(endDate);
				int id = (Integer) memberId;
				Contingent c = new Contingent(id, start, end);
				ContingentMapper cMapper = new ContingentMapper();
				cMapper.addContingent(c);
				MemberMapper mMapper = new MemberMapper();
				mMapper.changeMemberStatus(id);
				JOptionPane.showMessageDialog(null, "Kontingent er registreret!");
				addContingentFrame.setVisible(false);
			}	
		});
		
		cancelBtn = new JButton("Cancel");
		cancelBtn.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent arg0) {
				addContingentFrame.setVisible(false);
			}	
		});

		tablePanel = new JPanel(new BorderLayout());
		panelRight = new JPanel();
		
		contingentPanel = new JPanel();
		final BoxLayout bLayout = new BoxLayout(contingentPanel, BoxLayout.Y_AXIS);
		contingentPanel.setLayout(bLayout);
		btnPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
	
		tableScrollPane = new JScrollPane(membersTable);
		membersTable.setFillsViewportHeight(true);
		membersTable.getColumnModel().getColumn(0).setPreferredWidth(100);
		membersTable.setBorder(BorderFactory.createLineBorder(Color.black));
		membersTable.getTableHeader().setReorderingAllowed(false);
		membersTable.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() == 1) {
					panelRight.removeAll();
					contingentPanel.removeAll();
					membersTable = (JTable) e.getSource();
					int row = membersTable.getSelectedRow();
					
					memberId = (Object) membersTable.getValueAt(row, 0);
					Object fName = (Object) membersTable.getValueAt(row, 1);
					Object lName = (Object) membersTable.getValueAt(row, 2);
					
					memberIdLbl = new JLabel("MedlemsID: " + memberId);
					fNameLbl = new JLabel("Fornavn: " + fName);
					lNameLbl = new JLabel("<html>Fornavn: " + lName + "<br><br></html>");
					startDateLbl = new JLabel("Startdato: (eks.: 01-01-2013)");
					startDateTF = new JTextField(8);
					startDateTF.setText(startDateString);
					endDateLbl = new JLabel("Slutdato: (eks.: 01-02-2013)");
					endDateTF = new JTextField(8);
					contingentPanel.add(memberIdLbl);
					contingentPanel.add(fNameLbl);
					contingentPanel.add(lNameLbl);
					contingentPanel.add(startDateLbl);
					contingentPanel.add(startDateTF);
					contingentPanel.add(Box.createRigidArea(new Dimension(0, 10)));
					contingentPanel.add(endDateLbl);
					contingentPanel.add(endDateTF);
					panelRight.add(contingentPanel);
					panelRight.invalidate();
					panelRight.validate();
					panelRight.repaint();
				}
			}
		});
		DefaultTableCellRenderer leftRenderer = new DefaultTableCellRenderer();
		leftRenderer.setHorizontalAlignment(JLabel.LEFT);
		membersTable.getColumnModel().getColumn(0).setCellRenderer(leftRenderer);
		
		tablePanel.setBounds(10, 10, 300, 400);
		tablePanel.setLayout(new BorderLayout());
		tablePanel.add(membersTable.getTableHeader(), BorderLayout.NORTH);
		tablePanel.add(membersTable, BorderLayout.WEST);
		tablePanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

	    js = new JSeparator(JSeparator.VERTICAL);
	    
	    JLabel text = new JLabel("<html>Klik på et medlem til venstre for at tilføje kontingent.<br/><br/></html>");
	    panelRight.add(text);
		
		JPanel p1 = new JPanel();
		SpringLayout springLayout = new SpringLayout();
		p1.setLayout(springLayout);
		
		panelRight.add(p1);

		btnPanel.add(addBtn);
		btnPanel.add(cancelBtn);

		panelRightSide = new JPanel(new BorderLayout());
		panelRightSide.add(js, BorderLayout.WEST);
		panelRightSide.add(panelRight, BorderLayout.CENTER);
		panelRightSide.add(btnPanel, BorderLayout.SOUTH);
		
	}

	public void showGUI() {
		addContingentFrame = new JFrame();
		Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); 
		int w = addContingentFrame.getSize().width;
		int h = addContingentFrame.getSize().height;
		int x = (dim.width-w)/8;
		int y = (dim.height-h)/8;
		
		addContingentFrame.setTitle("Opret Kontingent");
		addContingentFrame.setLayout(new BorderLayout());
		addContingentFrame.setSize(700, 500);
		addContingentFrame.setLocation(x, y);
		addContingentFrame.add(tablePanel, BorderLayout.WEST);
		addContingentFrame.add(panelRightSide, BorderLayout.CENTER);
		addContingentFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		addContingentFrame.setVisible(true);
	}

	private static DateTime parseDateTime(String input) {
		String pattern = "dd-MM-yy";
		DateTime dateTime = DateTime.parse(input, DateTimeFormat.forPattern(pattern));		
		return dateTime;
	}
	
	class MyTableModel extends AbstractTableModel {

		private static final long serialVersionUID = 1L;
		private List<Member> members = new ArrayList<Member>();

		public MyTableModel(List<Member> members) {
			this.members = members;
		}

		public void addMember(Member m) {
			members.add(m);
			int row = members.size() - 1;
			fireTableRowsInserted(row, row);
		}

		public void removeMemberFromTable(int row) {
			members.remove(row);
			fireTableRowsDeleted(row, row);
		}

		public void tableUpdate(int row, Member m) {
			if (row >= 0 && row < members.size()) {
				members.set(row, m);
				fireTableRowsUpdated(row, row);
			}
		}

		public List<Member> getMembers() {
			return new ArrayList<Member>(members);
		}

		@Override
		public int getColumnCount() {
			return 3;
		}

		@Override
		public int getRowCount() {
			return members.size();
		}

		@Override
		public Object getValueAt(int rowIndex, int columnIndex) {
			Member m = members.get(rowIndex);

			switch (columnIndex) {
			case 0:
				return m.getMemberId();

			case 1:
				return m.getfName();

			case 2:
				return m.getlName();

			default:
				return "";
			}
		}

		public String getColumnName(int column) {
			switch (column) {
			case 0:
				return "MedlemsID";

			case 1:
				return "Fornavn";

			case 2:
				return "Efternavn";

			default:
				return "";
			}
		}

		public Class<?> getColumnClass(int columnIndex) {
			switch (columnIndex) {
			case 0:
				return Integer.class;

			case 1:
				return String.class;

			case 2:
				return String.class;

			default:
				return String.class;
			}
		}
	}
}
